﻿#region changelog
/*
 * 02/04/09 - wbw (Seagull Consulting): Original code
 * 02/13/09 - wbw : change file extension on TvDBXMLFile from mpg.xml to xml.  append xml to the OutputFile in the Profile to construct the file name.
 * 03/16/09 - wbw : change to pull series name from TheTVDB rather than from the input file name
 * 09/08/09 - wbw : change assumption that fileName will be in format ending with mpg.xml to ???.xml where ??? is the initial file type (e.g. mkv, mpg, etc.)
 */
#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace Durrant.Plugins.TvDB
{
    public class SageXMLFile
    {
        //Expect fileName as full path + including mpg.xml extension
        //09-08-09 - wbw Expect fileName as full path + including xml extension
        public bool create(string fileName, Series series, Episode episode)
        {
            StringBuilder XMLStream = null;
            StreamReader streamIn = null;
            StreamWriter streamOut = null;
            bool status = false;
            errorMessage = String.Empty;

            try
            {
                streamIn = new StreamReader(TVDB.TemplateXMLFileName);
                File.Copy(TVDB.TemplateXMLFileName, fileName, true);
                streamOut = new StreamWriter(fileName);
                XMLStream = new StringBuilder(streamIn.ReadToEnd());

                //Replace keywords in Template XML document 
                XMLStream = XMLStream.Replace(Constants.SERIES_NETWORK_XML, series.Network);
                XMLStream = XMLStream.Replace(Constants.SERIES_NAME_XML, series.SeriesName);
                XMLStream = XMLStream.Replace(Constants.EPISODE_NAME_XML, episode.Name);
                XMLStream = XMLStream.Replace(Constants.SERIES_GENRE_XML, series.Genre);
                XMLStream = XMLStream.Replace(Constants.EPISODE_OVERVIEW_XML, episode.Overview);
                XMLStream = XMLStream.Replace(Constants.EPISODE_FIRST_AIRED_XML, episode.FirstAired);
                XMLStream = XMLStream.Replace(Constants.SERIES_CONTENT_RATING_XML, series.ContentRating);
                XMLStream = XMLStream.Replace(Constants.SERIES_RUNTIME_XML, convertRunTime(series.RunTime));
                XMLStream = XMLStream.Replace(Constants.EPISODE_RECORD_DATETIME_XML, convertRecordTime(series.AirTime, episode));

                //New constraint is to just take last 8 chars of the string rather than assume the Template file is in form of .mpg.xml
                //This should fix problem where you might get an mpg or an mkv file extension
                //fileName = fileName.Substring(0, fileName.IndexOf(Constants.MPG_FILE_EXT + Constants.XML_FILE_EXT));
                fileName = fileName.Substring(0, fileName.Length - 8);

                XMLStream = XMLStream.Replace(Constants.EPISODE_FILENAME_XML,fileName);
                streamOut.Write(XMLStream.ToString());
                status = true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error reading/writing XML Template file: " + ex.Message);
                Debug.WriteLine(ex.ToString());
                errorMessage = ex.ToString();
                status = false;
            }
            finally
            {
                if (streamIn != null)
                    streamIn.Close();
                if (streamOut != null)
                    streamOut.Close();
            }

            return status;
        }

        private string convertRunTime(string runTime)
        {
            int convertRunTime = Convert.ToInt32(runTime);
            convertRunTime *= 6;
            return convertRunTime.ToString();
        }

        private string convertRecordTime(string recordTime, Episode episode)
        {
            DateTime adjustedRecordDate = new DateTime();
            DateTime localDateTime = new DateTime();
            TimeZone localTimeZone = TimeZone.CurrentTimeZone;
            localDateTime = DateTime.Now;
            int timeZoneOffset = 0;


            adjustedRecordDate = Convert.ToDateTime(episode.FirstAired + " " + recordTime);
            adjustedRecordDate = adjustedRecordDate.ToUniversalTime();
            timeZoneOffset = localTimeZone.GetUtcOffset(localDateTime).Hours;
            adjustedRecordDate = adjustedRecordDate.AddHours(-1*timeZoneOffset);

            return adjustedRecordDate.ToString("yyyy-MM-dd") + "T" + adjustedRecordDate.ToString("HH:mm:ss") + ".000Z";
        }
        public string errorMessage { get; set; }
    }
}
